package com.newture.lxz.plugins.mybatis;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.VisitableElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiao.hu
 * @date 2021-09-26
 * @apiNote
 */
public class OptimisticLockRewritePlugin extends PluginAdapter {

    /**
     * 重写 validate 返回true，插件才能生效
     * @param list
     * @return
     */
    @Override
    public boolean validate(List<String> list) {
        return true;
    }


    @Override
    public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        rewriteVersion(element, "record.version != null", "record.version == null");
        return true;
    }

    @Override
    public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        rewriteVersion(element, "version != null", "version == null");
        return true;
    }

    private void rewriteVersion(XmlElement element, String ifTestContent, String ifTestNewContent) {
        List<XmlElement> elToRewriteList = new ArrayList<>();
        List<VisitableElement> elements = element.getElements();
        for (VisitableElement el : elements) {

            if(el instanceof XmlElement) {
                XmlElement xmlElement = (XmlElement) el;
                List<VisitableElement>  velList = xmlElement.getElements();
                for(VisitableElement el1 : velList) {
                    if(el1 instanceof XmlElement) {
                        XmlElement xmlElement1 = (XmlElement) el1;
                        List<Attribute> attributes = xmlElement1.getAttributes();
                        for(Attribute attribute : attributes) {

                            if(ifTestContent.equals(attribute.getValue())) {
                                elToRewriteList.add(xmlElement1);
                            }
                        }
                    }
                }
            }
        }

        for(XmlElement el : elToRewriteList) {
            el.getAttributes().clear();
            el.addAttribute(new Attribute("test", ifTestNewContent));

            el.getElements().clear();
            el.addElement(new TextElement("version = version + 1,"));
        }
    }
}
